package com.kitty.game.fight.service;

import com.kitty.game.role.model.Role;
import com.kitty.game.config.PetSet;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.MoveEvent;
import com.kitty.mina.cache.DataCache;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Service

public class MonsterService {


    private ConcurrentMap<Integer, Integer> monsterTimes = new ConcurrentHashMap<>();

    public int updateMonsterTime(int roleId) {
        int pre = monsterTimes.getOrDefault(roleId, 0);
        monsterTimes.put(roleId, pre + 1);
        return pre + 1;
    }

    public void flushMonsterTime(int roleId) {
        monsterTimes.remove(roleId);
    }

    public List<PetSet> getMapMonster(int mapId) {
        ArrayList<PetSet> arrayList = new ArrayList<>();
        for (PetSet petSet :DataCache.ICON_PETSET.values()){
            if(petSet.getMapId()==mapId){
                arrayList.add(petSet);
            }
        }
        return arrayList;
    }

    @EventHandler(EventType.MOVE)
    public void handleMoveEvent(MoveEvent moveEvent) {
        /**遇野外怪处理*/
        Role role = moveEvent.getRole();
        if (role == null) {
            return;
        }
        /**不够等级时，不会遇到野外怪(任务怪在其他地方处理)*/
        if (role.getLevel() < Const.WILD_MONSTER_MIN_LEVEL) {
            return;
        }

        MonsterService monsterService = SpringUtils.getBean(MonsterService.class);
        FightService fightService = SpringUtils.getBean(FightService.class);
        int count = monsterService.updateMonsterTime(role.getRoleId());
        int mapId = role.getPos().getMapId();
        List<PetSet> mapMonster = monsterService.getMapMonster(mapId);
        if (mapMonster == null || mapMonster.size() <= 0) {
            return;
        }
        if (count >= 10 && !role.isAvoidMonster()) {
            Team team = fightService.getRoleFightTeam(role);
            fightService.enterFieldFight(team, role);
            monsterService.flushMonsterTime(role.getRoleId());
        }
    }
}
